package cj.web.portal.controllers;

import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.paoding.rose.web.Invocation;
import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.annotation.rest.Post;
import net.paoding.rose.web.var.Model;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import cj.web.admin.constants.Constants;
import cj.web.admin.utils.MD5Security;
import cj.web.kly.domain.Member;
import cj.web.login.controllers.BaseController;
import cj.web.portal.service.HomeService;
import cj.web.portal.service.LoginService;

/**
 * 首页
 * @author Administrator
 *
 */
@Path("")
public class HomeController extends BaseController {
	
	public static String news_columnsid="";//新闻动态 columnsId 3
	public static String announcement_columnsid="";//公告栏 columnsId 20
	public static String majorproject_columnsid="";//重大项目 columnsId 28,29
	public static String honoraryawards_columnsid="";//荣誉奖项 columnsId 11
	public static String gjjpt_columnsid="";//国家级平台 groupId 14,15
	public static String ysjpt_columnsid="";//院所平台 groupId 16
	public static String partyaffairs_columnsid="";//党群活动 columnsId 19
	public static String researchactivity_columnsid="";//科研进展 columnsId 15
	public static String industrynews_columnsid="";//行业动态 columnsId 17
	public static String academiccommunication_columnsid="";//学术交流 columnsId 16
	public static String sngzh_columnsid="";//所内公众号

	public static String News_And_Trends = "News_And_Trends";
	public static String Announcement = "Announcement";
	public static String Major_project = "Major_project";
	public static String Honorary_Awards = "Honorary_Awards";
	public static String Party_Affairs = "Party_Affairs";
	public static String Research_Activity = "Research_Activity";
	public static String Academic_Communication = "Academic_Communication";
	public static String Industry_News = "Industry_News";
	public static String gjjpt = "gjjpt";
	public static String sbjpt = "sbjpt";
	public static String ysjpt = "ysjpt";
	public static String HOME_SNGZH = "HOME_SNGZH";//所内公众号
	
	private static Logger logger = Logger.getLogger(HomeController.class.getName());
	
	private final static int isErrorCount = 5;
	
	private static String homeMemuKey = "0";
	
	@Autowired
	private LoginService loginService;
	@Autowired
	private HomeService homeService;
	
	/**
	 * 首页
	 * @param columnsId
	 * @param start
	 * @param length
	 * @return
	 * @throws ParseException
	 */
	@Get("")
	public String home(Model model,Invocation inv) throws ParseException {
		
		ServletContext context = inv.getServletContext();  
        HashMap dictionaryInfoMap = (HashMap)context.getAttribute("dictionaryInfoMap");
		Map rep = (Map) dictionaryInfoMap.get("configRep");
		
		news_columnsid=rep.get(News_And_Trends).toString().split("@")[1];//新闻动态 columnsId 3
		majorproject_columnsid=rep.get(Major_project).toString().split("@")[1];//荣誉奖项 columnsId 11
		partyaffairs_columnsid=rep.get(Party_Affairs).toString().split("@")[1];//党群活动 columnsId 19
		announcement_columnsid=rep.get(Announcement).toString().split("@")[1];//公告栏 columnsId 20
		honoraryawards_columnsid=rep.get(Honorary_Awards).toString().split("@")[1];//荣誉奖项 columnsId 11
		partyaffairs_columnsid=rep.get(Party_Affairs).toString().split("@")[1];//党群活动 columnsId 19
		researchactivity_columnsid=rep.get(Research_Activity).toString().split("@")[1];//科研进展 columnsId 15
		industrynews_columnsid=rep.get(Industry_News).toString().split("@")[1];//行业动态 columnsId 17
		academiccommunication_columnsid=rep.get(Academic_Communication).toString().split("@")[1];//学术交流 columnsId 16
		gjjpt_columnsid=rep.get(gjjpt).toString().split("@")[1];//国家级平台 groupId 14,15
		ysjpt_columnsid=rep.get(ysjpt).toString().split("@")[1];//院所平台 groupId 16
		sngzh_columnsid=rep.get(HOME_SNGZH).toString().split("@")[1];//所内公众号
		
		model = homeService.getHomeModel(model, news_columnsid, announcement_columnsid, 
				majorproject_columnsid, honoraryawards_columnsid, gjjpt_columnsid, 
				ysjpt_columnsid, partyaffairs_columnsid, 
				researchactivity_columnsid, industrynews_columnsid, academiccommunication_columnsid,sngzh_columnsid);
		model.add("homeMemuKey",homeMemuKey);
		return "/views/portal/index.vm";
	}
	
	@Post("login")
	public String login(Model model,@Param("account") String account,
			@Param("pwd") String pwd,HttpServletRequest request,
			HttpServletResponse response){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		try {
			Member member = loginService.queryByPhone(account);
			if(member==null){
				jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
				jo.put("msg","无此用户");
			}else if(member.getIsError()==isErrorCount){
				jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
				jo.put("msg","密码错误次数过多，请联系后台管理员解锁！");
			}else{
				if(member.getPwd().equals((MD5Security.md5(pwd)))){
					addCookie(response, "account", account);
					addCookie(response, "userId", String.valueOf(member.getId()));
					addCookie(response, "name", member.getName());
					addCookie(response, "_token_", MD5Security.returnSingKey(account));//种植的Key
				}else{
					loginService.updateErrorById(member.getId());
					jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
					jo.put("msg","密码不正确");
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
			jo.put("msg","异常!");
		}
		
		return "@"+jo.toString();
    }
	
	@Get("logout")
    public String logout(HttpServletRequest request,HttpServletResponse response){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		removeCookie(response, "account");
		removeCookie(response, "userId");
		removeCookie(response, "name");
		removeCookie(response, "_token_");
		return "@"+jo.toString();
    }
	
	@Post("updatePwd")
    public String updatePwd(@Param("newPwd") String newPwd,@Param("comfirmPwd") String comfirmPwd,
    		HttpServletRequest request,HttpServletResponse response) throws Exception{
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		if(newPwd.equals(comfirmPwd)){
			try {
				loginService.updatePwdForPortal(returnPortalSessionObj(request).getId(), 
						MD5Security.md5(newPwd));
			} catch (Exception e) {
				// TODO: handle exception
				jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
			}
			
		}else{
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		removeCookie(response, "account");
		removeCookie(response, "userId");
		removeCookie(response, "name");
		removeCookie(response, "_token_");
		return "@"+jo.toString();
    }
}